#include "thread.h"

namespace sylar{
    static thread_local Thread* threadp = nullptr;
    static thread_local std::string threadname = "unkonw";
    //为每个线程都开辟的副本信息用thread_local标识
    Thread::Thread(std::string name,func_t func)
        :_name(name),_func(func){
        //启动线程完成run任务
        int ret = pthread_create(&_tid,nullptr,Thread::run,this);
        if(ret != 0){
            //打印错误信息
            logmessage(FATAL,"phread create faild");
        }
        _seamphore.wait();// 等待初始化run函数初始化新线程的栈数据threadp和threadname，要不然当主线程调用get获取时就会出现问题
    }
    Thread::~Thread(){
        if(_tid){
            pthread_detach(_tid);
            _tid=0;
        }
    }
    pid_t Thread::getnowtid()// 获取系统分配的线程id
    {
        return syscall(SYS_gettid);//syscall(SYS_gettid)是一个系统调用，用于获取当前线程的唯一ID。SYS_gettid 是 Linux 特定的系统调用编号，用来获取线程ID (TID)。pid_t 是一个数据类型，用于表示进程ID或线程ID。
    }

    Thread* Thread::getnowthreadp()// 获取当前所在线程
    {
        return threadp;
    }

    const std::string& Thread::getnowname()//获取当前线程的名字
    {
        return threadname;
    }

    void Thread::setnowname(const std::string &name)//给当前线程设置名字
    {
        if (threadp)
        {
            threadp->_name =name;
        }
        threadname = name;
    }

    void* Thread::run(void* args){
        threadp = static_cast<Thread*>(args);

        threadname = threadp->_name;
        //logmessage(DEBUG,"%s",threadname.c_str());
        threadp->_pid = getnowtid(); //初始化线程局部变量

        pthread_setname_np(pthread_self(), threadp->_name.substr(0, 15).c_str()); //将名称设置进线程内
        threadp->_seamphore.signal();
        (threadp->_func)();//执行任务函数
        return nullptr;
    }
    void Thread::join(){
        if(_tid){
            int ret = pthread_join(_tid,nullptr);
            if(ret != 0){
                logmessage(ERROR,"pthread join faild");
            }
            _tid = 0;
        }
    }
};